<?php

/**
 * 自定义头部CSS样式，
 * 生成并输出自定义主题样式，包括容器宽度、背景颜色、顶部菜单样式等
 * @Author Dadong2g
 * @date   2023-03-14
 * @return void
 */
function custom_head_css() {
    $css = ''; // 初始化CSS字符串

    

    if (!empty($__css)) {
        $css .= "$__css";
    }

    //自定义CSS
    $custom_web_css = _xin('site_web_css');
    if ($custom_web_css) {
        $css .= $custom_web_css;
    }
    //打包输出
    if (!empty($css)) {
        echo "<style type=\"text/css\">\n" . $css . "\n</style>";
    }

}
add_action('wp_head', 'custom_head_css');



/**
 * 内页标题优化
 * 还原原始标题，移除WordPress默认添加的前缀文字
 *
 * @param string $title 当前标题
 * @param string $original_title 原始标题
 * @return string 优化后的标题
 */
function zb_archive_title($title, $original_title) {

    return $original_title; // 返回原始标题，不做修改
}
add_filter('get_the_archive_title', 'zb_archive_title', 10, 2);

/**
 * 内页描述优化
 * 优化归档页面描述，特别是搜索结果页面的描述信息
 *
 * @param string $description 默认描述文本
 * @return string 优化后的描述文本
 */
function zb_archive_description($description) {
    if (is_search()) { // 如果是搜索结果页面
        global $wp_query;
        $search_num  = $wp_query->found_posts; // 获取搜索结果数量
        // 格式化搜索结果描述
        $description = sprintf(__('搜索到 %1$s 个与 "%2$s" 相关的结果', 'woo'), $search_num, get_search_query());
    }
    return $description;
}
add_filter('get_the_archive_description', 'zb_archive_description');

// 在后台更新菜单时删除缓存
function zb_update_menu_callback() {
    delete_transient('main-menu-cache');
}
add_action('wp_update_nav_menu', 'zb_update_menu_callback', 10);

/**
 * 上一页翻页钩子替换
 * @Author Dadong2g
 * @date   2022-01-06
 * @param  [type]     $attr [description]
 * @return [type]
 */
function _prev_posts_link_attr($attr) {
    return $attr . ' class="prev"';
}
add_filter('previous_posts_link_attributes', '_prev_posts_link_attr');

/**
 * 下一页翻页钩子替换
 * @Author Dadong2g
 * @date   2022-01-06
 * @param  [type]     $attr [description]
 * @return [type]
 */
function _next_posts_link_attr($attr) {
    return $attr . ' class="next"';
}
add_filter('next_posts_link_attributes', '_next_posts_link_attr');


/**
 * 评论提交前处理
 * 控制评论功能是否开启，并过滤评论内容中的不安全标签
 *
 * @param array $commentdata 评论数据数组
 * @return array 处理后的评论数据
 */
function preprocess_close_comment($commentdata) {
    // 检查网站评论功能是否开启
    if (!is_site_comments()) {
        wp_die('本站评论系统暂未开启');exit;
    }

    $allowed_tags = array(
        'img' => array(
            'src' => array()
        ),
    );
    // 过滤不安全标签 
    $commentdata['comment_content'] = wp_kses($commentdata['comment_content'], $allowed_tags);
    
    return $commentdata;
}
add_filter('preprocess_comment', 'preprocess_close_comment');


/**
 * 评论通过后添加动态
 * 当评论被批准后，添加一条网站动态记录
 *
 * @param int $comment_id 评论ID
 * @param int $comment_approved 评论状态(1表示已批准)
 * @return void
 */
function dynamic_message_comment($comment_id, $comment_approved){
    // 仅当评论被批准时执行
    if( 1 === $comment_approved ){
        $comment = get_comment($comment_id); // 获取评论详情
        // 添加网站动态
        ZB_Dynamic::add([
            'info' => sprintf( __('评论了%s', 'woo'),get_the_title($comment->comment_post_ID) ),
            'uid' => $comment->user_id, 
            'href' => get_the_permalink($comment->comment_post_ID),
        ]);
    }
    
}

add_action( 'comment_post', 'dynamic_message_comment', 10, 2 );




/**
 * 过滤评论查询
 * 排除特定文章类型的评论，防止旧版本兼容性问题
 *
 * @param WP_Query $query 评论查询对象
 * @return void
 */
function filter_question_comments($query) {
    // 只在后台评论页面进行过滤
    if (is_admin() && $query->query_vars['type'] == '') {
        // 排除文章类型为question的评论
        $query->query_vars['post_type'] = array('post', 'page');
    }
}
add_action('pre_get_comments', 'filter_question_comments');


/**
 * 删除图片多余属性
 * @Author Dadong2g
 * @date   2022-01-06
 * @param  [type]     $html [description]
 * @return [type]
 */
function remove_img_attr($html) {
    return preg_replace('/(width|height)="\d+"\s/', "", $html);
}
add_filter('post_thumbnail_html', 'remove_img_attr');

/**
 * 自定义头像URL
 * 根据用户设置替换默认头像URL，支持多种头像类型
 *
 * @param string $url 默认头像URL
 * @param mixed $id_or_email 用户ID、邮箱或对象
 * @param array $args 头像参数
 * @return string 处理后的头像URL
 */
function _get_avatar_url($url, $id_or_email, $args) {
    $user_id = 0; // 初始化用户ID
    // 根据不同类型的$id_or_email参数获取用户ID
    if (is_numeric($id_or_email)) {
        $user_id = absint($id_or_email);
    } elseif (is_string($id_or_email) && is_email($id_or_email)) {
        $user = get_user_by('email', $id_or_email);
        if (isset($user->ID) && $user->ID) {
            $user_id = $user->ID;
        }
    } elseif ($id_or_email instanceof WP_User) {
        $user_id = $id_or_email->ID;
    } elseif ($id_or_email instanceof WP_Post) {
        $user_id = $id_or_email->post_author;
    } elseif ($id_or_email instanceof WP_Comment) {
        $user_id = $id_or_email->user_id;
        if (!$user_id) {
            $user = get_user_by('email', $id_or_email->comment_author_email);
            if (isset($user->ID) && $user->ID) {
                $user_id = $user->ID;
            }

        }
    }

    $avatar_url = get_default_avatar_src(); //默认头像

    $avatar_type = get_user_meta($user_id, 'user_avatar_type', true); // null | custom | qq | weixin | weibo |

    if ($avatar_type == 'custom' || $avatar_type == 'gravatar') {

        $custom_avatar = get_user_meta($user_id, 'user_custom_avatar', true);
        if (!empty($custom_avatar)) {

            if (strpos($custom_avatar, '/') === 0) {
                // 相对路径，添加网站目录前缀
                //兼容老款相对地址
                $uploads = wp_upload_dir();
                if (file_exists(WP_CONTENT_DIR . '/uploads' . $custom_avatar)) {
                    $custom_avatar = WP_CONTENT_URL . '/uploads' . $custom_avatar;
                }
            } else {
                // 绝对路径，直接输出
                $avatar_url = $custom_avatar;
            }

            $avatar_url = set_url_scheme($custom_avatar); //头像存在
        }

    } elseif (in_array($avatar_type, ['qq', 'weixin', 'weibo'])) {
        $avatar_url = set_url_scheme(get_user_meta($user_id, 'open_' . $avatar_type . '_avatar', true)); //开发平台
    }

    return preg_replace('/^(http|https):/i', '', $avatar_url);

}

add_filter('get_avatar_url', '_get_avatar_url', 10, 3);

function _pre_get_avatar($avatar, $id_or_email, $args) {

    $url = get_avatar_url($id_or_email, $args);

    $class = array('avatar-img', 'avatar', 'avatar-' . (int) $args['size']);
    if ($args['class']) {
        if (is_array($args['class'])) {
            $class = array_merge($class, $args['class']);
        } else {
            $class[] = $args['class'];
        }
    }

    $avatar = sprintf(
        "<img alt='%s' src='%s' class='%s' height='%d' width='%d' %s/>",
        esc_attr($args['alt']),
        esc_url($url),
        esc_attr(join(' ', $class)),
        (int) $args['height'],
        (int) $args['width'],
        $args['extra_attr']
    );
    return $avatar;
}
add_filter('pre_get_avatar', '_pre_get_avatar', 10, 3);

function zb_login_url($url, $redirect) {
    $url = home_url('/login');
    if (!empty($redirect)) {
        $url = add_query_arg('redirect_to', urlencode($redirect), $url);
    }
    return esc_url($url);
}
//add_filter('login_url', 'zb_login_url', 20, 2);

function zb_register_url($url) {
    $url = home_url('/register');
    return esc_url($url);
}
add_filter('register_url', 'zb_register_url', 20);

function zb_lostpassword_url($url, $redirect) {
    $url = home_url('/lostpwd');
    if (!empty($redirect)) {
        $url = add_query_arg('redirect_to', urlencode($redirect), $url);
    }
    return esc_url($url);
}
add_filter('lostpassword_url', 'zb_lostpassword_url', 20, 2);

// 禁用自动生成的图片尺寸
function zb_disable_image_sizes($sizes) {
    if (_xin('disable_wp_thumbnail_crop', false)) {
        $sizes = array();
    }

    return $sizes;
}
add_action('intermediate_image_sizes_advanced', 'zb_disable_image_sizes');


/**
 * 搜素功能过滤器
 * @Author Dadong2g
 * @date   2023-02-13
 * @param  [type]     $search   [description]
 * @param  [type]     $wp_query [description]
 * @return [type]
 */
function site_search_by_title_only($search, $wp_query) {
    global $wpdb;

    if (empty($search) || empty(_xin('is_site_pro_search_title', false))) {
        return $search; // skip processing - no search term in query
    }

    // skip processing - no search term in query
    $q      = $wp_query->query_vars;
    $n      = !empty($q['exact']) ? '' : '%';
    $search = $searchand = '';
    foreach ((array) $q['search_terms'] as $term) {
        $term = esc_sql($wpdb->esc_like($term));
        $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
        $searchand = ' AND ';
    }
    if (!empty($search)) {
        $search = " AND ({$search}) ";
        if (!is_user_logged_in()) {
            $search .= " AND ($wpdb->posts.post_password = '') ";
        }

    }
    return $search;

}
add_filter('posts_search', 'site_search_by_title_only', 99, 2);


/**
 * 广告代码输出
 * 根据不同位置和设备类型输出相应的广告代码
 *
 * @param string $slug 广告位置标识
 * @return void
 */
function zb_xin_ads_filter($slug) {
    // AJAX请求不显示广告
    if (defined('DOING_AJAX') && DOING_AJAX) {
        return false;
    }

    $position   = (strpos($slug, 'bottum') !== false) ? ' bottum' : ' top';
    $is_ads     = _xin($slug);
    $ads    = _xin($slug . '_' );

    $html = '';
    if ($is_ads && isset($ads)) {
        $html = ' 
                <div class="container-fluid">';
        $html .= $ads;
        $html .= '</div>';
    }
    echo $html;
}

// 头部广告
add_action('wp_head', function() {
    do_action('xin_ads', 'ad_top');
}, 10);

// 底部广告
add_action('wp_footer', function() {
    do_action('xin_ads', 'ad_bottum');
}, 10);

add_action('xin_ads', 'zb_xin_ads_filter', 10, 1);







// 演示数据导入 需要安装 One Click Demo Import 插件
// src="/wp-content/uploads/.*?\.png"
// 
//
//function zb_ocdi_import_files() {
//  return [
//    [
//      'import_file_name'           => '演示风格1',
//      'categories'                 => [],
//      'import_file_url'            => 'https://ripro.rizhuti.com/ripro-demo-file/ripro-v5-content.xml',
//      'import_widget_file_url'     => 'https://ripro.rizhuti.com/ripro-demo-file/ripro-v5-widgets.json',
//      'import_customizer_file_url' => '',
//      'import_redux'               => [],
//      'import_preview_image_url'   => 'https://ripro.rizhuti.com/ripro-demo-file/demo1.jpg',
//      'preview_url'                => 'https://ripro.rizhuti.com/',
//    ]
//  ];
//}
//add_filter( 'ocdi/import_files', 'zb_ocdi_import_files' );
//
//
//function zb_ocdi_after_import_setup() {
//
//    if (false) {
//        $file_url = 'https://ripro.rizhuti.com/ripro-demo-file/ripro-v5-options.json';
//        $json_data = file_get_contents( $file_url );
//        $import_data  = json_decode( $json_data, true );
//        $options = ( is_array( $import_data ) && ! empty( $import_data ) ) ? $import_data : array();
//        update_option( _OPTIONS_PRE , $options); //更新主题设置
//    }
//
//    // Assign menus to their locations.
//    $main_menu = get_term_by( 'name', 'main', 'nav_menu' );
//
//    set_theme_mod( 'nav_menu_locations', [
//            'main-menu' => $main_menu->term_id, // replace 'main-menu' here with the menu location identifier from register_nav_menu() function in your theme.
//        ]
//    );
//    delete_transient('main-menu-cache');//删除菜单缓存
//    //重写固定连接规则
//    flush_rewrite_rules(false);
//}
//add_action( 'ocdi/after_import', 'zb_ocdi_after_import_setup' );